package demo;

import java.io.*;
import java.net.*;

import flex.messaging.io.SerializationContext;
import flex.messaging.io.amf.Amf3Output;
import flex.messaging.io.amf.Amf3Input;

public class AMF3 {
	private SerializationContext sc = null;

	private Amf3Output amfout = null;

	private Amf3Input amfin = null;

	public AMF3() {

		System.out.println("创建AMF3数据处理对象");

		sc = new SerializationContext();
	}

	// 发送数据方法
	public void sendAmfData(Object objout, Socket socket) {

		System.out.println("AMF3_发送数据对象");

		if (sc != null) {

			if (amfout == null) {

				amfout = new Amf3Output(sc);

			}
		}

		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		DataOutputStream dos = new DataOutputStream(baos);

		amfout.setOutputStream(dos);

		try {

			amfout.writeObject(objout);

		} catch (IOException e) {

			e.printStackTrace();

		}

		byte[] buf = baos.toByteArray();

		try {

			OutputStream os = socket.getOutputStream();

			os.write(buf);

		} catch (IOException e) {

			e.printStackTrace();
		}
	}

	// 读取数据方法
	public Object receiveAmfData(Socket socket) {

		System.out.println("AMF3_接收数据对象");

		if (sc != null) {

			if (amfin == null) {

				amfin = new Amf3Input(sc);

			}
		}

		byte[] buf = new byte[1024];

		ByteArrayInputStream bais = new ByteArrayInputStream(buf);

		DataInputStream dis = new DataInputStream(bais);

		amfin.setInputStream(dis);

		try {

			InputStream is = socket.getInputStream();

			is.read(buf);

		} catch (IOException e) {

			e.printStackTrace();

		}

		Object objin = null; /* 创建一个Object对象; */

		try {

			objin = amfin.readObject();

		} catch (ClassNotFoundException e) {

			e.printStackTrace();

		} catch (IOException e) {

			e.printStackTrace();

		}

		return objin;
	}
}
